<template>
  <view class="contract-container">
    <!-- 导航栏 -->
    
    <!-- 自定义导航栏 -->
    <view class="custom-nav-bar">
      <nav-bar></nav-bar>
      <view class="right">
        <text v-if="hasContract" class="contract-status">已上传合同</text>
      </view>
    </view>

    <!-- 合同上传区域 -->
    <view class="upload-section">
      <view class="section-title">合同照片</view>
      <view class="upload-area">
        <!-- 已上传的合同照片 -->
        <view 
          class="contract-item" 
          v-for="(item, index) in contractImages" 
          :key="index"
        >
          <image 
            :src="item.url" 
            mode="aspectFill" 
            @tap="previewImage(index)"
          ></image>
          <view class="status-tag" :class="item.status">
            {{ item.statusText }}
          </view>
          <text class="delete-btn" @tap="deleteImage(index)" v-if="item.status === 'pending'">×</text>
        </view>

        <!-- 上传按钮 -->
        <view 
          class="upload-btn" 
          @tap="chooseImage" 
          v-if="contractImages.length < maxImages && !hasContract"
        >
          <text class="iconfont icon-camera"></text>
          <text>上传合同照片</text>
          <text class="tip">请上传清晰的合同照片</text>
        </view>
      </view>
    </view>

    <!-- 上传说明 -->
    <view class="upload-tips">
      <view class="tip-title">
        <text class="iconfont icon-info"></text>
        <text>上传说明</text>
      </view>
      <view class="tip-content">
        <text>1. 请确保上传的合同照片清晰完整</text>
        <text>2. 支持jpg、png格式的图片</text>
        <text>3. 单张图片大小不超过5MB</text>
        <text>4. 最多可上传{{ maxImages }}张合同照片</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <button 
      class="submit-btn" 
      :class="{ disabled: !hasUnsavedImages || hasContract }"
      @tap="submitImages"
      v-if="!hasContract"
    >
      提交审核
    </button>
  </view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
  data() {
    return {
      maxImages: 6, // 最大上传数量
      contractImages: [], // 合同图片列表
      hasUnsavedImages: false, // 是否有未保存的图片
      techId: '', // 技师ID
      technicianInfo: null, // 技师信息
      hasContract: false // 是否已有合同
    }
  },

  onLoad() {
    // 从本地存储获取techId
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.techId) {
      this.techId = userInfo.techId
      // 获取已上传的合同
      this.loadContractImages()
    } else {
      uni.showToast({
        title: '未找到技师信息',
        icon: 'none'
      })
    }
  },

  methods: {
    goBack() {
      uni.navigateBack()
    },

    // 加载已上传的合同图片
    async loadContractImages() {
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const result = await uni.request({
          url: `${uni.$config.baseUrl}/technician/technician/${this.techId}`,
          method: 'GET',
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          }
        })

        if (result.data.code === 200) {
          this.technicianInfo = result.data.data
          
          // 检查技师信息中的合同数据
          if (this.technicianInfo) {
            // 检查是否有合同
            this.hasContract = this.technicianInfo.contract != null
            
            // 清空合同图片列表
            this.contractImages = []
            
            // 如果存在合同，添加一张合同图片
            if (this.hasContract && this.technicianInfo.contract) {
              const urls = this.technicianInfo.contract.split(',')
              if (urls.length > 0) {
                this.hasContract = true
                urls.forEach((u, idx) => {
                  this.contractImages.push({
                    url: u,
                    status: 'approved',
                    statusText: '已通过',
                    id: idx
                  })
                })
              } else {
                this.hasContract = false
              }
            }
          }
        }
      } catch (err) {
        console.error('获取技师信息失败:', err)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 选择图片
    chooseImage() {
      // 如果已有合同，不允许上传
      if (this.hasContract) return
      
      uni.chooseImage({
        count: this.maxImages - this.contractImages.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 添加新选择的图片到列表
          const newImages = res.tempFilePaths.map(path => ({
            url: path,
            status: 'pending',
            statusText: '待审核'
          }))
          this.contractImages = [...this.contractImages, ...newImages]
          this.hasUnsavedImages = true
        }
      })
    },

    // 预览图片
    previewImage(index) {
      const urls = this.contractImages.map(item => item.url)
      uni.previewImage({
        urls,
        current: urls[index]
      })
    },

    // 删除图片
    deleteImage(index) {
      // 如果已有合同，不允许删除
      if (this.hasContract) return
      
      uni.showModal({
        title: '提示',
        content: '确定要删除这张合同照片吗？',
        success: (res) => {
          if (res.confirm) {
            this.contractImages.splice(index, 1)
            this.hasUnsavedImages = this.contractImages.some(item => item.status === 'pending')
          }
        }
      })
    },

    // 提交图片
    async submitImages() {
      if (!this.hasUnsavedImages || this.hasContract) return

      const pendingImages = this.contractImages.filter(item => item.status === 'pending')
      if (pendingImages.length === 0) return

      uni.showLoading({
        title: '提交中...'
      })

      try {
        // 上传所有待审核的图片
        for (const image of pendingImages) {
          await this.uploadImage(image.url)
        }

        uni.showToast({
          title: '提交成功',
          icon: 'success'
        })

        // 重新加载合同列表
        this.loadContractImages()
        this.hasUnsavedImages = false
      } catch (err) {
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },

    // 上传单张图片
    uploadImage(filePath) {
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync('token')
        console.log('upload token =>', token)
        if (!token) {
          uni.showToast({ title:'请先登录', icon:'none' })
          uni.hideLoading()
          return reject(new Error('no token'))
        }

        uni.uploadFile({
          url   : `${uni.$config.baseUrl}/contract/contract/upload`,
          filePath,
          name  : 'file',
          formData : { technicianId: this.techId },
          header   : { Authorization: `Bearer ${token}` },
          success  : res => {
            const data = JSON.parse(res.data || '{}')
            if (data.code === 200) {
              // 上传成功，仅返回后端透传的数据
              resolve(data)
            } else {
              reject(new Error(data.msg || '上传失败'))
            }
          },
          fail     : reject
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.contract-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 120rpx;
  padding-top: 88rpx;

  .custom-nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    height: 88rpx;
    background: #FFFFFF;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    z-index: 100;
    
    .left {
      width: 88rpx;
      display: flex;
      align-items: center;
      
      .iconfont {
        font-size: 36rpx;
        color: #333333;
      }
    }
    
    .center {
      flex: 1;
      text-align: center;
      font-size: 32rpx;
      color: #333333;
      font-weight: 500;
    }
    
    .right {
      width: 140rpx;
      text-align: right;
      
      .contract-status {
        font-size: 24rpx;
        color: #2B85E4;
        padding: 4rpx 10rpx;
        background-color: #E9F3FE;
        border-radius: 12rpx;
      }
    }
  }

  .upload-section {
    margin-top: 20rpx;
    background: #FFFFFF;
    padding: 30rpx;

    .section-title {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 20rpx;
    }

    .upload-area {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;

      .contract-item {
        position: relative;
        width: 216rpx;
        height: 216rpx;
        border-radius: 12rpx;
        overflow: hidden;

        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .status-tag {
          position: absolute;
          top: 0;
          right: 0;
          padding: 4rpx 12rpx;
          font-size: 24rpx;
          color: #FFFFFF;
          
          &.pending {
            background: #FF9500;
          }
          
          &.approved {
            background: #4CD964;
          }
          
          &.rejected {
            background: #FF3B30;
          }
        }

        .delete-btn {
          position: absolute;
          top: 0;
          right: 0;
          width: 40rpx;
          height: 40rpx;
          background: rgba(0, 0, 0, 0.5);
          color: #FFFFFF;
          font-size: 32rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }

      .upload-btn {
        width: 216rpx;
        height: 216rpx;
        background: #FFFFFF;
        border: 2rpx dashed #DDDDDD;
        border-radius: 12rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        
        .iconfont {
          font-size: 48rpx;
          color: #999999;
          margin-bottom: 10rpx;
        }
        
        text {
          font-size: 26rpx;
          color: #333333;
          
          &.tip {
            font-size: 22rpx;
            color: #999999;
            margin-top: 6rpx;
          }
        }
      }
    }
  }

  .upload-tips {
    margin: 30rpx;
    background: #FFFFFF;
    border-radius: 12rpx;
    padding: 20rpx;

    .tip-title {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      
      .iconfont {
        font-size: 32rpx;
        color: #2B85E4;
        margin-right: 10rpx;
      }
      
      text {
        font-size: 28rpx;
        color: #333333;
        font-weight: 500;
      }
    }

    .tip-content {
      text {
        display: block;
        font-size: 26rpx;
        color: #666666;
        line-height: 1.6;
      }
    }
  }

  .submit-btn {
    position: fixed;
    left: 30rpx;
    right: 30rpx;
    bottom: 30rpx;
    height: 88rpx;
    line-height: 88rpx;
    background: #2B85E4;
    color: #FFFFFF;
    font-size: 32rpx;
    border-radius: 44rpx;
    border: none;
    
    &.disabled {
      background: #CCCCCC;
    }
  }
}
</style> 